package org.robot.scm.platform.monitor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.platform.AbstractMonitor;
import org.robot.scm.pojos.BaseNotify;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.pojos.platform.SinoBaseNotify;
import org.robot.scm.utils.BaiduSpeakUtil;
import org.robot.scm.utils.DateTool;
import org.robot.scm.utils.RequestHelper;

/**
 * 三诺生物
 */
@Slf4j
public class SinoNoticeMonitor extends AbstractMonitor {

    @Override
    public PlatformEnum getPlatform() {
        return PlatformEnum.SINO;
    }

    @Override
    public BaseNotify doMonitor(BaseConfig config) {
        try {
            // 先获取最新设备
            Map<String, String> headers = new HashMap<String, String>() {{
                put("sino-Auth", config.getCurrentPlatform().getToken());
                put("Host", "ican.sinocare.com");
                put("xweb_xhr", "1");
            }};
            String deviceResult = RequestHelper.get("https://ican.sinocare.com/api/sino-device/v1/user-device/get-used-cgm?familyUserId=", headers);
            JSONObject deviceObject = JSON.parseObject(deviceResult);
            // 重新授权
            if (deviceObject.getInteger("code") == 401) {
                String token = authorization();
                config.getCurrentPlatform().setToken(token);
                headers.put("sino-Auth", token);
            }
            String deviceSn = deviceObject.getInteger("code") == 200 ? deviceObject.getJSONObject("data").getString("usingSn") : StringUtils.EMPTY;
            long thisTime = System.currentTimeMillis();
            long preTime = thisTime - 18000000L; // 最近五小时的数据
            String result = RequestHelper.get(String.format(config.getCurrentPlatform().getNoticeSrc(), deviceSn, preTime, thisTime), headers);
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.getInteger("code") != 200) {
                return null;
            }
            JSONArray glucoseData = jsonObject.getJSONArray("data");
            if (Objects.isNull(glucoseData) || glucoseData.isEmpty()) {
                return null;
            }

            return glucoseData.getJSONObject(0).toJavaObject(SinoBaseNotify.class);
        } catch (Exception e) {
            log.warn("sino error: {}", e.getMessage());
            return null;
        }
    }

    private String authorization() {
        Map<String, String> headers = new HashMap<String, String>() {{
            put("sino-Auth", "Basic bWluaWFwcC1zbmprOmFjNjc0NTljN2QzYjZlYjc1MjIzMDl1bWE3NjZyMDBh");
            put("Authorization", "Basic bWluaWFwcC1zbmprOmFjNjc0NTljN2QzYjZlYjc1MjIzMDl1bWE3NjZyMDBh");
            put("Host", "ican.sinocare.com");
            put("xweb_xhr", "1");
        }};
        String authUrl = "https://ican.sinocare.com/api/sino-auth/oauth/token?tenantId=000000&grant_type=wechat&scope=all&type=account&union_id=opm8mw3EinYtCSL0nQ_0Y_1fsIdc&open_id=oWXSX5MgKZEENu0hi6zhlB0pT-0c";
        String authResult = RequestHelper.post(authUrl, headers, new JSONObject());
        JSONObject authObject = JSON.parseObject(authResult);
        return authObject.getString("access_token");
    }

    @Override
    public void doAfter(BaseConfig config, BaseNotify notice) {
        SinoBaseNotify thisNotice = (SinoBaseNotify) notice;
        //夜间低血糖提醒并播报
        if (config.get().getNightMode().isNight(config) && thisNotice.isLowGlucose(config)) {
            speak(config, thisNotice);
            return;
        }
        //白天血糖异常提醒并播报
        if (!config.get().getNightMode().isNight(config) && thisNotice.isAbnormal(config)) {
            speak(config, thisNotice);
        }
    }

    private void speak(BaseConfig config, SinoBaseNotify thisNotice) {
        if (!config.getCurrentPlatform().isPlaySound()) {
            return;
        }
        String nowDate = DateTool.format(new Date(), DateTool.PATTERN_4);
        StringBuilder text = new StringBuilder("现在时间是 " + nowDate + ", 您的血糖值为:  " + thisNotice.getValue());
        if (thisNotice.getValue() < 3.9) {
            text.append(" ,血糖有点低, 请注意防范低血糖风险");
        }
        if (thisNotice.getValue() > 10) {
            text.append(" ,血糖非常高, 请注意控制您的饮食");
        }
        BaiduSpeakUtil.speak(text.toString());
    }
}
